import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:get/get.dart';
import 'package:multi_image_picker_view/multi_image_picker_view.dart';
import 'package:path_provider/path_provider.dart';
// import 'package:simple_native_image_compress/simple_native_image_compress.dart';
import 'package:study_demo/api/bean.dart';
import 'package:study_demo/base/BaseController.dart';
import 'package:study_demo/base/rename_controller.dart';
import 'package:study_demo/ui/tool/picture_conduct/resize_dialog.dart';

import 'package:image/image.dart' as img;
import 'package:path/path.dart' as path;

class PictureConductDetailController extends BaseController
    with RenameController {
  final type = 0.obs;

  final format = 'jpg'.obs;

  final filePath = ''.obs;
  final file = File('').obs;

  final imageList = <ImageFile>[].obs;

  @override
  onInit() {
    super.onInit();
  }

  chooseFormat(String value) {
    format.value = value;
  }

  changeType(int conductType) {
    type.value = conductType;
  }

  transform() async {
    imageList.value = pickController.images.toList();
    if (imageList.isEmpty) {
      toast('请至少添加一张图片');
      return;
    }
    imageList.forEach((element) async {
      File file = File(element.path!);
      final bytes = await file.readAsBytes();
      final image = img.decodeImage(bytes);
      var convertedImageBytes;
      switch (format.value) {
        case 'jpg':
        case 'jpeg':
          convertedImageBytes = img.encodeJpg(image!);
          break;
        case 'png':
          convertedImageBytes = img.encodePng(image!);
          break;
        case 'webp':
          // convertedImageBytes = await convertImageToWebp(element);
          break;
        case 'ico':
          convertedImageBytes = img.encodeIco(image!);
          break;
      }
      final directory = await getApplicationDocumentsDirectory();
      final fileName = path.basenameWithoutExtension(element.path!);
      final newFileName = "$fileName.${format.value}";
      Directory tempDirectory = Directory(directory.path + '\\output');
      if (!tempDirectory.existsSync()) {
        tempDirectory.createSync();
      }

      // 重新组合目录和新的文件名
      final newName = path.join(tempDirectory.path, newFileName);
      final outputFile = File(newName);
      await outputFile.writeAsBytes(convertedImageBytes);

      toast('操作成功');
    });
  }

  // Future<List<int>> convertImageToWebp(ImageFile imageFile) async {
  //   final result = await ImageCompress.contain(
  //     filePath: imageFile.path!,
  //     maxWidth: 2048,
  //     maxHeight: 2048,
  //     compressFormat: CompressFormat.webP,
  //     samplingFilter: FilterType.lanczos3,
  //   );
  //   return result;
  // }

  reSize() async {
    imageList.value = pickController.images.toList();
    if (imageList.isEmpty) {
      toast('请至少添加一张图片');
      return;
    }
    var result = await Get.dialog(ResizeDialog());
    if (result != null && result is ImageSize) {
      print('isMainAspect:${result.isMaintainAspect}');
      imageList.forEach((element) async {
        await adjustImageSize(element.path!, result);
      });
      toast('修改成功');
    }
  }

  adjustImageSize(String imagePath, ImageSize imageSize) async {
    // 读取图片
    final bytes = await File(imagePath).readAsBytes();
    final img.Image? imgData = img.decodeImage(bytes);

    // 调整图片大小
    final resizedImage = !imageSize.isMaintainAspect!
        ? img.copyResize(imgData!,
            width: imageSize.width,
            height: imageSize.height,
            maintainAspect: false)
        : img.copyResize(imgData!,
            width: imageSize.width, maintainAspect: true);

    // 将调整后的图片编码回字节流

    var resizedBytes;

    switch (format.value) {
      case 'jpg':
      case 'jpeg':
        resizedBytes = img.encodeJpg(resizedImage, quality: 80);
        break;
      case 'png':
        resizedBytes = img.encodePng(resizedImage);
        break;
      case 'webp':
        resizedBytes = img.encodeJpg(resizedImage, quality: 80);
        break;
      case 'ico':
        resizedBytes = img.encodeIco(resizedImage);
        break;
    }

    final directory = await getApplicationDocumentsDirectory();
    final fileName = path.basename(imagePath);
    Directory tempDirectory = Directory(directory.path + '\\output');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }

    // 重新组合目录和新的文件名
    final newName = path.join(tempDirectory.path, fileName);

    // 创建临时文件并写入数据
    final tempFile = File(newName);
    await tempFile.writeAsBytes(resizedBytes);
  }

  outputDirectory() async {
    final directory = await getApplicationDocumentsDirectory();
    FilePicker.platform
        .pickFiles(initialDirectory: directory.path + '\\output\\');
  }
}
